import {
  Message
} from 'element-ui'
import types from './types'
import { getIssues, getIssue, getComments } from '@/api'

// 获取 issue 列表
const getIssuesAction = async ({ commit, state, rootState }, {
  page = 1,
  perPage
} = {}) => {
  const currentRepo = rootState.repos.currentRepo
  perPage = perPage || state.perPage

  commit(types.SET_PAGE_INFO, { issuesLoading: true })
  const issues = await getIssues({
    namespace: currentRepo,
    page,
    per_page: perPage
  })

  commit(types.SET_ISSUES, issues)
  commit(types.SET_CURRENT_REPO, currentRepo)
  commit(types.SET_PAGE_INFO, {
    issuesLoading: false,
    issuesLoaded: issues.length < perPage,
    page
  })
}

// 获取 issue 列表下一页
const getIssuesNextPageAction = async ({ commit, state, rootState }) => {
  const currentRepo = rootState.repos.currentRepo
  const page = state.page + 1
  const perPage = state.perPage

  commit(types.SET_PAGE_INFO, { issuesLoading: true })

  const issues = await getIssues({
    namespace: currentRepo,
    page,
    per_page: perPage
  })

  commit(types.SET_ISSUES, [].concat(state.issues, issues))
  commit(types.SET_CURRENT_REPO, currentRepo)
  commit(types.SET_PAGE_INFO, {
    issuesLoading: false,
    issuesLoaded: issues.length < perPage,
    page
  })
}

const getIssueAction = async ({ commit, rootState }, { number, currentRepo }) => {
  currentRepo = currentRepo || rootState.repos.currentRepo
  commit(types.SET_PAGE_INFO, { issueLoading: true })
  commit(types.SET_CURRENT_REPO, currentRepo)
  let issue = null
  try {
    issue = await getIssue({
      namespace: currentRepo,
      number: number
    })
  } catch (err) {
    console.error(err)
    err.message && Message.error(err.message)
  }
  commit(types.SET_PAGE_INFO, {
    issueLoading: false,
    issueLoaded: true
  })
  commit(types.SET_CURRENT_ISSUE, issue)
}

const getIssueCommentsAction = async ({ commit, state }, { url, page }) => {
  if (state.commentsLoading) {
    return
  }
  if (page === 1) {
    commit(types.SET_CURRENT_COMMENTS, [])
    commit(types.SET_PAGE_INFO, {
      commentsLoaded: false
    })
  } else if (!page) {
    page = state.commentsPage + 1
  }
  commit(types.SET_PAGE_INFO, {
    commentsLoading: true
  })
  let comments = []
  try {
    comments = await getComments({
      url,
      page,
      per_page: state.commentsPerPage
    })
  } catch (err) {
    console.error(err)
    err.message && Message.error(err.message)
  }
  commit(types.SET_CURRENT_COMMENTS, state.currentComments.concat(comments))
  commit(types.SET_PAGE_INFO, {
    commentsLoading: false,
    commentsPage: page,
    commentsLoaded: comments.length < state.commentsPerPage
  })
}

export default {
  getIssues: getIssuesAction,
  getIssuesNextPage: getIssuesNextPageAction,
  getIssue: getIssueAction,
  getIssueComments: getIssueCommentsAction
}
